const { Router } = require("express");
const Role = require("../model/Role");

const router = new Router();

// 新增角色
router.post("/", async (req, res) => {
  const { name, menus } = req.body;
  
  if (!name) {
    res.status(400).json({ message: "角色名不能为空！" });
    return;
  }

  if (!menus || !menus.length) { 
    return res.status(400).json({ message: "角色权限不能为空" });
  }
  await Role.create({
    name: name,
    createTime: new Date().getTime(),
    menus
  });
  res.json({ message: "新增成功！" });
});

// 修改角色
router.patch("/", async (req, res) => {
  const { id } = req.body;
  if (!id) {
    res.status(400).json({ message: "参数不能为空！" });
    return;
  }
  const {name, checked, halfChecked} = req.body;
  const options = {};
  //是否需要修改名字
  if(name){
    options.name = name;
  }
  //修改全选的权限
  if(checked){
    options.checked = checked;
  }
  //修改半选的权限
  if(halfChecked){
    options.halfChecked = halfChecked;
  }

  await Role.findByIdAndUpdate(id, options);
  res.json({ message: "更新成功！" });
});

// 删除角色
router.delete("/", async (req, res) => {
  const { id } = req.query;
  if (!id) {
    res.status(400).json({ message: "参数不能为空！" });
    return;
  }
  await Role.findByIdAndDelete(id);
  res.json({ message: "删除成功！" });
});

//根据创建时间获取角色列表
router.get("/", async (req, res) => {
  const page = Number(req.query.page);
  const count = Number(req.query.count);
  if (!page || !count) {
    res.status(400).json({ message: "参数不能为空！" });
    return;
  }
  const [total, data] = await Promise.all([
    //查询总数
    Role.countDocuments(),
    // 查询当前页的数据
    Role.find()
    .sort({ createTime: -1 })
    .skip((page - 1) * count)
    .limit(count)
  ]);
  res.json({total, data});
});


//获取角色详情
router.get("/:id", async (req, res) => {
  const page = Number(req.query.page);
  const count = Number(req.query.count);
  if (!req.params.id) {
    res.status(400).json({ message: "参数不能为空！" });
    return;
  }
  const [data] = await Promise.all([
    //查询总数
    // Role.countDocuments(),
    // 查询当前页的数据
    Role.find({_id: req.params.id})
    // .sort({ createTime: -1 })
    // .skip((page - 1) * count)
    // .limit(count)
  ]);
  res.json({data:data.length ? data[0] : '角色不存在'});
});

router.get("/all", async (req, res)=>{
  // const data = await Role.find();
  console.log(111);
  res.json({a:111});
})

module.exports = router;
